package com.spikegpsongoogleappengine;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.AlertDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.MultiAutoCompleteTextView;
import android.widget.SimpleAdapter;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.spikegpsongoogleappengine.datasource.CompanyInfoDataSource;
import com.spikegpsongoogleappengine.datasource.CompanyInfoDummyDataSource;

public class Search extends MapActivity implements OnClickListener {
	private static final String TAG = "Search";
	private MapView mapView;
	private Button button;
	// private MultiAutoCompleteTextView textView;
	private EditText textViewSearch;

	private MyLocationOverlay myLocationOverlay;
	private LinearLayout searchPanel;
	private ListView listView;
	private CompanyInfoDataSource dataSource = new CompanyInfoDummyDataSource();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search);

		mapView = (MapView) findViewById(R.id.mapview2);
		mapView.setBuiltInZoomControls(true);
		myLocationOverlay = new MyLocationOverlay(Search.this, mapView);
		myLocationOverlay.enableMyLocation();

		MapController controller = mapView.getController();
		if (myLocationOverlay.getMyLocation() != null) {
			controller.setZoom(15);
			controller.animateTo(myLocationOverlay.getMyLocation());
		} else {
			controller.setZoom(8);
			GeoPoint mkdGeoPoint = new GeoPoint((int) (41.607228 * 1E6),
					(int) (21.747437 * 1E6));
			controller.animateTo(mkdGeoPoint);
		}

		Log.d(TAG, "Putting markers on screen");
		Drawable drawable = getResources().getDrawable(R.drawable.marker_blue);
		drawable.setBounds(0, 0, 32, 37);
		RegularCompanyInfoOverlay mapOverlay = new RegularCompanyInfoOverlay(
				drawable, this);
		List<Overlay> listOfOverlays = mapView.getOverlays();
		listOfOverlays.clear();
		// mapOverlay.setCompanyInfos(CompanyInfoDummyDataSource
		// .getRandomCompanyInfo(5));
		listOfOverlays.add(mapOverlay);

		button = (Button) findViewById(R.id.searchButton);
		button.setOnClickListener(this);
		// textView = (MultiAutoCompleteTextView)
		// findViewById(R.id.multiAutoCompleteTextView1);

		searchPanel = (LinearLayout) findViewById(R.id.searchPanel);

		TabHost tabs = (TabHost) findViewById(R.id.tabhost);

		configureTextViewSearch();

		configureListViewCompaniesInfo();

		tabs.setup();

		TabSpec tab_one = tabs.newTabSpec("tab_one_btn_tab");
		tab_one.setContent(R.id.mapview2);
		tab_one.setIndicator("Map");
		tabs.addTab(tab_one);

		TabSpec tab_two = tabs.newTabSpec("tab_two_btn_tab");
		tab_two.setContent(R.id.tab_2);
		tab_two.setIndicator("List");
		tabs.addTab(tab_two);

		getDefaultMarkers();

	}

	private void configureListViewCompaniesInfo() {
		// listView.setTextFilterEnabled(true);

		listView = (ListView) findViewById(R.id.tab_2);

		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {

				@SuppressWarnings("unchecked")
				String s = ((Map<String, String>) listView.getAdapter()
						.getItem(arg2)).get("FnOrgUrl").toString();

				Toast.makeText(getApplicationContext(), arg2 + "-" + s,
						Toast.LENGTH_SHORT).show();

				Intent intent = new Intent(getApplicationContext(),
						SpecificCompanyInfoInteraction.class);

				startActivity(intent);

			}
		});

	}

	private void configureTextViewSearch() {
		textViewSearch = (EditText) findViewById(R.id.search_text_field);
		// textViewSearch.requestFocus();

		TextView.OnEditorActionListener searchTextListener = new TextView.OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView v, int actionId,
					KeyEvent event) {

				if (actionId == EditorInfo.IME_NULL
						&& event.getAction() == KeyEvent.ACTION_DOWN) {
					// example_confirm();//match this behavior to your 'Send'
					// (or Confirm) button

					Toast.makeText(getApplicationContext(), "voalaaa",
							Toast.LENGTH_SHORT).show();

					handleSearchEvent();

				}
				return true;
			}
		};
		textViewSearch.setOnEditorActionListener(searchTextListener);
	}

	private class ClickListener implements OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {

			// ((TextView) arg1).setText("ggg");

			Toast.makeText(getApplicationContext(), "f", Toast.LENGTH_SHORT)
					.show();

			// ListView l = (ListView) arg1;

			// displayMessage("Clicked");
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		myLocationOverlay.enableMyLocation();
	}

	@Override
	protected void onPause() {
		super.onPause();
		myLocationOverlay.disableMyLocation();
	}

	private void getDefaultMarkers() {
		final String textFieldText = textViewSearch.getText().toString();
		Log.d(TAG, "Inserted text: " + textFieldText);
		new AsyncTask<Void, Void, Void>() {
			@Override
			protected Void doInBackground(Void... arg0) {
				Double lat = null;
				Double lng = null;
				GeoPoint geoPoint = myLocationOverlay.getMyLocation();
				if (geoPoint != null) {
					lat = geoPoint.getLatitudeE6() / 1e6;
					lng = geoPoint.getLongitudeE6() / 1e6;
				}

				List<CompanyInfo> companyInfos = dataSource.getCompanies(
						textFieldText, lat, lng);
				addCompaniesToScreen(companyInfos);
				addCompaniesToList(companyInfos);
				Log.d(TAG, "The companyInfos are collected in the background");

				return null;
			}
		}.execute();

	}

	private void addCompaniesToScreen(final List<CompanyInfo> companyInfos) {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				Log.d(TAG, "Putting markers on screen");
				Drawable drawable = getResources().getDrawable(
						R.drawable.marker_blue);
				drawable.setBounds(0, 0, 32, 37);
				RegularCompanyInfoOverlay mapOverlay = new RegularCompanyInfoOverlay(
						drawable, Search.this);
				List<Overlay> listOfOverlays = mapView.getOverlays();
				listOfOverlays.clear();
				listOfOverlays.add(mapOverlay);
				listOfOverlays.add(myLocationOverlay);
				mapOverlay.setCompanyInfos(companyInfos);

				mapView.invalidate();

			}

		});

	}

	private void addCompaniesToList(final List<CompanyInfo> companyInfos) {
		runOnUiThread(new Runnable() {

			@Override
			public void run() {
				Log.d(TAG, "Putting companies in list");
				List<Map<String, String>> companyInfoList = new ArrayList<Map<String, String>>();
				for (CompanyInfo companyInfo : companyInfos) {
					Map<String, String> data = new HashMap<String, String>();
					data.put("FnOrgUrl", companyInfo.getFnOrgUrl());
					companyInfoList.add(data);
				}
				int[] to = new int[] { R.id.list_item_txt_field };
				SimpleAdapter adapter = new SimpleAdapter(Search.this,
						companyInfoList, R.layout.list_item,
						new String[] { "FnOrgUrl" }, to);
				listView.setAdapter(adapter);
				// listView.setAdapter(new ArrayAdapter<Object>(Search.this,
				// R.layout.list_item, companyInfoList.toArray()));
			}

		});

	}

	public void myClickHandler(View v) {

		// reset all the listView items background colours
		// before we set the clicked one..
		// int count = listView.getCount();
		// for (int i=0; i < listView.getCount(); i++)
		// {
		// listView.getChildAt(i).setBackgroundColor(Color.BLUE);
		// }
		//
		//
		// //get the row the clicked button is in
		// LinearLayout vwParentRow = (LinearLayout)v.getParent();
		//
		// TextView child = (TextView)vwParentRow.getChildAt(0);
		// Button btnChild = (Button)vwParentRow.getChildAt(1);
		// btnChild.setText(child.getText());
		// btnChild.setText("I've been clicked!");
		//
		// int c = Color.CYAN;
		//
		// vwParentRow.setBackgroundColor(c);
		// vwParentRow.refreshDrawableState();
		// listView.getSelectedView().setBackgroundColor(Color.CYAN);
		// Button btnChild = (Button) v;

		// btnChild.setText("I've been clicked!");

		ListView tV = (ListView) v;

		tV.setBackgroundColor(Color.YELLOW);

		// listView.refreshDrawableState();
	}

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	@Override
	public void onClick(View v) {
		// displayMessage("click");

		if (v == findViewById(R.id.searchButton)) {

			handleSearchEvent();

		}

		getDefaultMarkers();
	}

	private void handleSearchEvent() {
		Toast.makeText(getApplicationContext(), "aPU", Toast.LENGTH_SHORT)
				.show();

	}

	private void displayMessage(String text) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(text).setCancelable(false);
		AlertDialog alert = builder.create();
		alert.show();
	}

}
